package com.ias.agdis_r.activity.mine;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.toolbox.Volley;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.bean.fight.Query;
import com.ias.agdis_r.bean.fight.QueryParams;
import com.ias.agdis_r.bean.other.AreaBean;
import com.ias.agdis_r.bean.other.LimitBean;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.request.AutotaskRequest;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.response.AutotaskResponse;
import com.ias.agdis_r.terminalmanager.restful.flight.vo.AutoTaskVO;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.SecurityUtil;
import com.ias.agdis_r.util.ShowToast;
import com.ias.agdis_r.volley.GsonRequest;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorAdapter;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorListener;
import com.ias.agdis_r.volley.callback.BaseOnVolleySuccessListener;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class ApplySettingActivity extends BaseKeyActivity {

	private ActionBar actionBar;

	private Spinner spLockType,spLockArea;
	private Button btnResType;
	private ArrayAdapter<String> adapterLockType,adapterLockArea;
	private EditText edit_lock_num;
	private Button btnSubmit;
	private int nIndexLock = -1;
	private int nIndexArea  = -1;
	private Dialog dialog = null;
	private List<Map<String, Object>> mDataResType = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> dataLockType = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> mChooseResType = new ArrayList<Map<String, Object>>();// 选中的资源类型
	private boolean isMultiselect = false;// 多资源锁定标识
	private List<Query> jsonLine = new ArrayList<Query>();
	private QueryParams query = new QueryParams();
	private RequestQueue requestQueue;
	private AutotaskRequest autotaskRequest;
	private List<AreaBean>  areaList = null;
	private BaseOnVolleySuccessListener<AutotaskResponse> successListener = new BaseOnVolleySuccessListener<AutotaskResponse>() {

		@Override
		public void onRequestSuccess(AutotaskResponse response) {
			if ("20010".equals(response.getHeader().getErrorCode())) {
				toast(response.getHeader().getErrorMessage());
			} else {
				toast(getString(R.string.lockItemSucceed));
				edit_lock_num.setText("");
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(edit_lock_num.getWindowToken(), 0);
			}
		}

		@Override
		public void onRequestFailed(BaseResponseHeader header) {
			// TODO Auto-generated method stub
			toast(header.getErrorMessage());
		}
	};
	private BaseOnVolleyErrorListener errorListener = new BaseOnVolleyErrorAdapter() {
		@Override
		public void onErrorOccurred(com.android.volley.VolleyError e) {
			String msg = "";
			if (e instanceof TimeoutError) {

				msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_timeout);
			} else if (e instanceof ServerError) {
				//显示接收消息异常
				msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_servererror);
			} else if (e instanceof NoConnectionError) {
				msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_noconnection);
			}
			toast(msg);
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_applysetting);
		actionBar = getActionBar();
		initactionBarApplySetting();
		isMultiselect = DataBaseManager.getInstance().getBoolean(ParameterModel.T_CHOOSELOCK,
				ParameterModel.MULTISELECT_ISUSING);
		requestQueue = Volley.newRequestQueue(this);
		initRequest();
		initView();
		initEvent();
	}

	private void initEvent() {
		btnSubmit.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				initQueryParams();
			}
		});
	}

	protected void submit() {
		query.setQueryParams(jsonLine);
		autotaskRequest.getAutoTaskVO().setParams(query);
		Request<AutotaskResponse> request = null;
		try {
			request = new GsonRequest<AutotaskResponse>(RestfulUri.getUri(MessageModel.TTAQ),
                    AutotaskResponse.class, DataManager.getInstance().getMapper().writeValueAsString(autotaskRequest), this.successListener, this.errorListener);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		requestQueue.add(request);
	}

	private void initRequest() {
		autotaskRequest = new AutotaskRequest();
		autotaskRequest.setHeader(SecurityUtil.getCommonRequestHeaderObject(MessageModel.TTAQ));
		AutoTaskVO autoTaskVO = new AutoTaskVO();
		autoTaskVO.setOpe("Y");
		autotaskRequest.setAutoTaskVO(autoTaskVO);
	}

	private void initView() {
		btnResType = (Button) findViewById(R.id.apply_lock_res_type);
		spLockType = (Spinner) findViewById(R.id.apply_lock_type);
		spLockArea = (Spinner) findViewById(R.id.apply_lock_area);
		edit_lock_num = (EditText) findViewById(R.id.apply_lock_input);
		btnSubmit = (Button) findViewById(R.id.apply_submit);
		adapterLockType = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		adapterLockType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapterLockArea = new  ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		adapterLockArea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		loadData();
		btnResType.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				showDialog();
			}
		});
		spLockType.setAdapter(adapterLockType);
		spLockArea.setAdapter(adapterLockArea);
		spLockType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				nIndexLock = arg2;
				edit_lock_num.setHint(getString(R.string.write) + spLockType.getSelectedItem().toString());
				String lockType = S.valueOf(dataLockType.get(nIndexLock).get(MessageModel.LOCK_ITEM_LOCK_TYPE));
				adapterLockArea.clear();
				if(ParameterModel.LOCK_TYPE_PLACECODE.equals(lockType)) {
					areaList = JavaBeanManager.getInstance().getPlaceAreaList();
					spLockArea.setVisibility(View.VISIBLE);
				}else if(ParameterModel.LOCK_TYPE_GTNAME.equals(lockType)){
					areaList = JavaBeanManager.getInstance().getGtnAreaList();
					spLockArea.setVisibility(View.VISIBLE);
				}else if(ParameterModel.LOCK_TYPE_BLT.equals(lockType)){
					areaList = JavaBeanManager.getInstance().getBltAreaList();
					spLockArea.setVisibility(View.VISIBLE);
				}else if(ParameterModel.LOCK_TYPE_PSN.equals(lockType)) {
					areaList = JavaBeanManager.getInstance().getPsnAreaList();
					spLockArea.setVisibility(View.VISIBLE);
				}else{
					areaList =null;
					spLockArea.setVisibility(View.INVISIBLE);
				}
				if(areaList!=null){
					for(AreaBean areaBean:areaList){
						String name = areaBean.getName();
						adapterLockArea.add(name);
					}
					adapterLockArea.notifyDataSetChanged();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		spLockArea.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				nIndexArea = arg2;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		spLockType.setSelection(0);
		spLockArea.setSelection(0);
	}

	private void loadData() {
		adapterLockType.clear();
		mDataResType.clear();
		String sRtl = JavaBeanManager.getInstance().getUserinfo().getRtl();
		if (S.isEmpty(sRtl)) {
			String sRes = JavaBeanManager.getInstance().getUserinfo().getRtp();
			HashMap<String, Object> hmDataR = new HashMap<String, Object>();
			hmDataR.put(MessageModel.LOCK_ITEM_TYPE, sRes);
			hmDataR.put(MessageModel.LOCK_ITEM_TYPE_NAME, getString(R.string.defaultResourcesType));
			mDataResType.add(hmDataR);
		} else {
			String[] sRtlArray = sRtl.split(",");
			for (int n = 0; n < sRtlArray.length - 1; n = n + 2) {
				HashMap<String, Object> hmDataR = new HashMap<String, Object>();
				hmDataR.put(MessageModel.LOCK_ITEM_TYPE, sRtlArray[n]);
				hmDataR.put(MessageModel.LOCK_ITEM_TYPE_NAME, sRtlArray[n + 1]);
				mDataResType.add(hmDataR);
			}
		}
		for (int i = 0; i < ParameterModel.LOCKTYPENAMEMAP.length; i++) {
			HashMap<String, Object> lockTypes = new HashMap<String, Object>();
			lockTypes.put(MessageModel.LOCK_ITEM_LOCK_TYPE, ParameterModel.LOCKTYPENAMEMAP[i][0]);
			lockTypes.put(MessageModel.LOCK_ITEM_LOCK_TYPE_NAME, ParameterModel.LOCKTYPENAMEMAP[i][1]);
			dataLockType.add(lockTypes);
			adapterLockType.add(ParameterModel.LOCKTYPENAMEMAP[i][1]);
		}
	}

	public void initQueryParams() {
		jsonLine.clear();
		String lockType = S.valueOf(dataLockType.get(nIndexLock).get(MessageModel.LOCK_ITEM_LOCK_TYPE));
		String num = edit_lock_num.getText().toString().trim();
		if (!isValid(num,lockType)) {
			toast(getString(R.string.writeRight));
			return;
		}else if(mChooseResType.size() == 0){
			toast(getString(R.string.chooseResourcesType2));
			return;
		}else{
			String[] numArrStar = num.split("\\*");
			String type = "";
			if(areaList !=null) {
				AreaBean area = areaList.get(nIndexArea);
				if(area!=null){
					type = area.getKey();
				}
			}
	
			for (int i = 0; i < mChooseResType.size(); i++) {
				String sRtp = S.valueOf(mChooseResType.get(i).get(MessageModel.LOCK_ITEM_TYPE));
				for (int j = 0; j < numArrStar.length; j++) {
					String[] numArrWell = numArrStar[j].split("#");
					if (numArrWell.length == 2) {
						int num2 = Integer.parseInt(numArrWell[1])+1;
						for (int num1 = Integer.parseInt(numArrWell[0]); num1 < num2; num1++) {
							String value = "";
							//如果数字小于10，且是起始数字前面第一位是0
							if(num1<10&&numArrWell[0].startsWith("0")){
								value = type+"0"+String.valueOf(num1);
							}else {
								value = type + String.valueOf(num1);
							}
							Query mqp = new Query();
							mqp.setTYPE(lockType);
							mqp.setRTP(sRtp);
							mqp.setVALUE(value);
							jsonLine.add(mqp);
						}
					} else if (numArrWell.length == 1) {
						String value = type+numArrWell[0];
						Query mqp = new Query();
						mqp.setTYPE(lockType);
						mqp.setRTP(sRtp);
						mqp.setVALUE(value);
						jsonLine.add(mqp);
					}
				}
			}
			for (Query query : jsonLine) {
				Iterator<Map<String, Object>> iter = JavaBeanManager.getInstance().getLockData().iterator();
				while (iter.hasNext()) {
					Map<String, Object> item = iter.next();
					if (item.get(MessageModel.LOCK_ITEM_LOCK_TYPE).equals(lockType)
							&& item.get(MessageModel.LOCK_PSN_TYPE).equals(query.getRTP())
							&& item.get(MessageModel.NUM).equals(query.getVALUE())) {
						toast(getString(R.string.lockItemExist));
						return;
					}
				}
			}
			if (isMultiselect) {
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				ShowNumDialog(getString(R.string.ASA_1)+jsonLine.size()+getString(R.string.ASA_2));
			}else {
				submit();
			}
		}
		return;
	}

	private void ShowNumDialog(String message){
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.prompt));
		builder.setMessage(message);
		builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				submit();
				dialog.dismiss();
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), null);
		dialog = builder.create();
		dialog.show();
	}

	private void toast(String msg) {
		if (S.isNotEmpty(msg)) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
		}
	}

	private boolean isValid(String str,String lockType) {
		if (S.isEmpty(str))
			return false;

		if (isMultiselect) {
			return checkMultiStr(str);
		} else {
			return checkNormalStr(str);
		}
	}

	/**
	 * 检测是否符合限制条件
	 * @param slock
	 * @return
	 */
	private boolean checkLimit(String slock){
		if(areaList ==null) {
			return true;
		}
		AreaBean areaBean = areaList.get(nIndexArea);
		List<LimitBean> areaList = areaBean.getLimitList();
		for(LimitBean limit:areaList){
			if(LimitBean.TYPE_NUM_NORMAL.equals(limit.getType())){
				String strat = limit.getStart();
				String end  =  limit.getEnd();
				try {
					int istart = Integer.parseInt(strat);
					int iend = Integer.parseInt(end);
					int ilock = Integer.parseInt(slock);
					//前面字母不包含0
					//如果锁定的数字在区间范围内
					if(!slock.startsWith("0")&&istart<=ilock&&ilock<=iend){
						return true;
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}else if(LimitBean.NUM_ZEROSTART.equals(limit.getType())){
				String strat = limit.getStart();
				String end  =  limit.getEnd();
				try {
					int istart = Integer.parseInt(strat);
					int iend = Integer.parseInt(end);
					int ilock = Integer.parseInt(slock);
					//如果锁定的数字在区间范围内
					if(istart<=ilock&&ilock<=iend){
						//如果锁定项大于等于10  或
						//如果锁定项小于10，前面字母不包含0，不符合限制条件
						if(ilock>=10||ilock<10&&slock.startsWith("0")) {
							return true;
						}
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}else if(LimitBean.GROUP.equals(limit.getType())){
				Set<String> includeSet = limit.getIncludeSet();
				if(includeSet!=null) {
					for(String include:includeSet){
						if(slock.toUpperCase().equals(include)){
							//符合条件
							return true;
						}
					}
				}
			}
		}
		return false;
	}
	private boolean checkMultiStr(String str){
		Pattern pattern = Pattern.compile("^[A-Za-z0-9]+$");
		String[] strStar = str.split("\\*");
		if (strStar.length == 0) {
			return false;
		}
		for (int i = 0; i < strStar.length; i++) {
			String[] strWell = strStar[i].split("#");
			if (strWell.length == 1) {
				if (S.isEmpty(strWell[0]) || !pattern.matcher(strWell[0].trim()).matches()||!checkLimit(strWell[0])) {
					return false;
				}
			}else if(strWell.length == 2) {
				int intStr0 = -1;
				int intStr1 = -1;
				try {
					intStr0 = Integer.parseInt(strWell[0]);
					intStr1 = Integer.parseInt(strWell[1]);
				}catch (NumberFormatException e){
					return false;
				}
				if (S.isEmpty(strWell[0])|| S.isEmpty(strWell[1]) || !pattern.matcher(strWell[0].trim()).matches() || !pattern.matcher(strWell[1].trim()).matches()
						|| intStr0 >= intStr1 ||!checkLimit(strWell[0])||!checkLimit(strWell[1])) {
					return false;
				}
			}else{
				return false;
			}
		}
		return true;
	}

	private boolean checkNormalStr(String str){
		Pattern pattern = Pattern.compile("^[A-Za-z0-9]+$");
		if (!pattern.matcher(str.trim()).matches()) {
			return false;
		}
		return true;
	}

	@SuppressLint("InflateParams")
	private void initactionBarApplySetting() {
		actionBar.setCustomView(
				LayoutInflater.from(ApplySettingActivity.this).inflate(R.layout.actionbar_back_and_home, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.txt_title);
		title.setText(R.string.ApplySettingActivity);
		ImageView back = (ImageView) findViewById(R.id.action_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		ImageView home = (ImageView) findViewById(R.id.action_home);
		home.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ApplySettingActivity.this, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
	}

	private void showDialog() {
		final List<String> strResLock = new ArrayList<String>();
		for (int i = 0; i < mDataResType.size(); i++) {
			strResLock.add(mDataResType.get(i).get(MessageModel.LOCK_ITEM_TYPE_NAME).toString());
		}
		final boolean[] selectBoolean = new boolean[strResLock.size()];
		AlertDialog.Builder builder = new AlertDialog.Builder(ApplySettingActivity.this);
		builder.setTitle(getString(R.string.resourcesType2));
		if (isMultiselect) {
			builder.setMultiChoiceItems(
					strResLock.toArray(new String[strResLock.size()]),
					selectBoolean,
					new DialogInterface.OnMultiChoiceClickListener() {
						@Override
						public void onClick(DialogInterface dialogInterface,
											int which, boolean isChecked) {
							selectBoolean[which] = isChecked;
						}
					});
			builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialogInterface, int which) {
					mChooseResType.clear();
					StringBuffer sb = new StringBuffer();
					for (int i = 0; i < selectBoolean.length; i++) {
						if (selectBoolean[i] && sb.length() == 0) {
							sb.append(strResLock.get(i));
							mChooseResType.add(mDataResType.get(i));
						} else if (selectBoolean[i]) {
							sb.append("," + strResLock.get(i));
							mChooseResType.add(mDataResType.get(i));
						}
					}
					if (sb.length() == 0) {
						btnResType.setText(getString(R.string.chooseResourcesType));
					} else {
						btnResType.setText(sb.toString());
					}
					dialog.dismiss();
				}
			});
		}else {
			builder.setSingleChoiceItems(strResLock.toArray(new String[strResLock.size()]),
					0, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							mChooseResType.clear();
							mChooseResType.add(mDataResType.get(which));
							btnResType.setText(strResLock.get(which));
							dialog.dismiss();
						}
					});
		}
		builder.setNegativeButton(getString(R.string.cancel), null);
		dialog = builder.create();
		dialog.show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(null != requestQueue)
		requestQueue.stop();
	}
}
